package com.rovinj_server.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rovinj_server.R;
import com.rovinj_server.adapter.InventroyAdapter;
import com.rovinj_server.adapter.PeopleRecyclerAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.Inventory;
import com.rovinj_server.entity.InventoryBarodeLocation;
import com.rovinj_server.entity.InventorySub;
import com.rovinj_server.entity.People;
import com.rovinj_server.utisl.DialogUtil;
import com.rovinj_server.utisl.Directory;
import com.rovinj_server.utisl.ExcelUtil;
import com.rovinj_server.utisl.ExcelUtils;
import com.rovinj_server.utisl.FileUtils;
import com.rovinj_server.view.InventoryRecordPopWindow;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jxl.write.WriteException;

/**
 * Created by Administrator on 2017/5/5.
 */

public class InventryActivity extends AutoLayoutActivity implements InventoryRecordPopWindow.OnSelectScanRecordItemClickListener {

    public List<Inventory> mDataList = new ArrayList();
    @Bind(R.id.jia_lmage)
    ImageView mJiaLmage;
    @Bind(R.id.relative_layout)
    RelativeLayout mRelativeLayout;
    @Bind(R.id.list_view)
    ListView mListView;
    @Bind(R.id.butt_barode)
    Button mButtBarode;
    @Bind(R.id.butt_location)
    Button mButtLocation;
    @Bind(R.id.add_qty1)
    TextView mAddQty1;
    @Bind(R.id.add_qty2)
    TextView mAddQty2;
    private ProgressDialog accessNetDialog;
    private InventroyAdapter mAdapter;
    private PeopleRecyclerAdapter peopleRecyclerAdapter;
    private DBManager mManager;
    private List<InventorySub> mSubDataList = new ArrayList<>();
    private List<InventorySub> mSubDataNull = new ArrayList<>();
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory);
        this.mContext = this;
        ButterKnife.bind(this);
        hidStater();
        initView();


    }

    private void initView() {
        mManager = new DBManager(InventryActivity.this);
        mManager.copyDBFile();
        mDataList = mManager.findDataList();
        mAdapter = new InventroyAdapter(this, mDataList);
        mListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onStart() {
        super.onStart();
        get_qty(0);
    }

    private void get_qty(final int i) {
        final ProgressDialog accessNetDialog = new ProgressDialog(this);
        accessNetDialog.setCanceledOnTouchOutside(false);
        DialogUtil.showDialog(accessNetDialog, "正在获取数据，请稍候...");
        new Thread(new Runnable() {
            @Override
            public void run() {

                if (i == 1) {
                    mDataList.clear();
                    mDataList = mManager.findDataList();
                    mAdapter.setListDataBean(mDataList);

                }
                mSubDataList = mManager.findSubDataList();
                mSubDataNull = mManager.findSubDataNull("location");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == 1) {
                            mAdapter.notifyDataSetChanged();
                        }
                        if (mSubDataList != null && mSubDataList.size() > 0) {
                            mAddQty1.setText(mSubDataList.size() + "");
                        }
                        if (mSubDataNull != null && mSubDataNull.size() > 0) {
                            mAddQty2.setText(mSubDataNull.size() + "");
                        }
                        accessNetDialog.dismiss();


                    }
                });

            }
        }).start();
    }


    private void set_dismissColse() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DialogUtil.dismissDialog(accessNetDialog);
            }
        });

    }

    /**
     * 隐藏状态栏
     */
    private void hidStater() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
    }


    @OnClick({R.id.jia_lmage, R.id.fh, R.id.butt_barode, R.id.butt_location})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jia_lmage:
                onPopupButtonClick(mJiaLmage);
                break;
            case R.id.fh:
                finish();
                break;
            case R.id.butt_barode: //
                flag = true;
                get_Xls();
                break;
            case R.id.butt_location: //
                flag = false;
                get_Xls();
                break;
        }
    }


    private void get_Xls() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); //开启选择一个文件数据
        intent.setType("*/*");  // 选择数据类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"), 1);
    }


    private boolean flag = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = data.getData();
                    final String path = FileUtils.getPath(InventryActivity.this, uri);
                    accessNetDialog = new ProgressDialog(this);
                    accessNetDialog.setCanceledOnTouchOutside(false);
                    DialogUtil.showDialog(accessNetDialog, "正在获取数据，请稍候...");
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            if (flag) {

                                Inventory mData = null;
                                try {
                                    mData = importExcelData(path);
                                } catch (Exception e) {
                                    set_Message(3, "excel文件损坏，请创建空白excel文件把损坏excel文件数据复制过来");
                                }
                                if (mData != null) {
                                    try {
                                        DBManager dbManager = new DBManager(InventryActivity.this);
                                        dbManager.copyDBFile();
                                        long rowid = dbManager.insertInventoryData(mData);
                                        mData.setId((int) rowid);
                                        mDataList.add(mData);
                                        mSubDataList = mManager.findSubDataList();
                                    } catch (Exception e) {
                                        set_Message(3, "excel存储失败");
                                    }
                                }

                                Message msg = new Message();
                                msg.what = 1;
                                Handler.sendMessage(msg);
                                //获取到数据保存到sqlite中

                            } else {
                                try {
                                    List<InventoryBarodeLocation> inventoryBarodeLocations = set_Location(path);//设置货位比配条码
                                    //获取到数据保存到sqlite中
                                    DBManager dbManager = new DBManager(InventryActivity.this);
                                    dbManager.copyDBFile();

                                    dbManager.updateCodeLocation(inventoryBarodeLocations);
                                    mSubDataNull = mManager.findSubDataNull("location");
                                    set_Message(1, "");
                                } catch (Exception e) {
                                    set_Message(3, "请确认是否导入库位excel文件，如果导入正确的库位excel文件可能excel文件损坏，请创建空白excel文件把损坏库位excel文件数据复制过来");

                                }
                            }
                        }
                    }.start();
                }
                break;
        }
    }

    private void set_Message(int i, String str) {
        Message msg = new Message();
        msg.what = i;
        msg.obj = str;
        Handler.sendMessage(msg);
    }

    //设置货位比配条码
    private List<InventoryBarodeLocation> set_Location(String path) {
        List<List<Object>> lists = ExcelUtil.read(path);
        List<InventoryBarodeLocation> mListBean = new ArrayList<>();
        if (lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                InventoryBarodeLocation inventoryBarodeLocation = new InventoryBarodeLocation();
                for (int j = 0; j < lists.get(i).size(); j++) {
                    switch (j) {
                        case 0:
                            inventoryBarodeLocation.setCode(lists.get(i).get(j).toString()); //条码
                            break;
                        case 1:
                            inventoryBarodeLocation.setLocation(lists.get(i).get(j).toString()); //条码
                            break;
                    }
                }
                mListBean.add(inventoryBarodeLocation);
            }
        }
        return mListBean;
    }

    public Inventory importExcelData(String path) {
        String[] split = path.split("/");
        List<List<Object>> lists = ExcelUtil.read(path);
        Inventory data = new Inventory();
        if (lists.size() > 1) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String t = format.format(new Date());
            int numcode = (int) ((Math.random() * 9 + 1) * 1000);
            data.setDepotName(t + "");
            data.setNumber((split[split.length - 1]));
            List<InventorySub> ListBean = new ArrayList<>();
            //跳过第一行标题
            for (int i = 1; i < lists.size(); i++) {
                InventorySub mInventorySub = new InventorySub();
                for (int j = 0; j < lists.get(i).size(); j++) {
                    switch (j) {
                        case 0:
                            mInventorySub.setBarode(lists.get(i).get(j).toString()); //条码
                            break;
                        case 1:
                            mInventorySub.setCode(lists.get(i).get(j).toString());  //款号
                            break;
                        case 2:
                            mInventorySub.setSjnumber(lists.get(i).get(j).toString()); //实际数
                            mInventorySub.setLessThan(Integer.parseInt(lists.get(i).get(j).toString())); //实际数
                            break;

                        default:
                            break;
                    }
                }
                ListBean.add(mInventorySub);
            }
            data.setQty(ListBean.size());
            data.setInventorySubList(ListBean);
        }
        return data;
    }

    private Handler Handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    DialogUtil.dismissDialog(accessNetDialog);
                    if (mSubDataList != null && mSubDataList.size() > 0) {
                        mAddQty1.setText(mSubDataList.size() + "");
                    }
                    if (mSubDataNull != null && mSubDataNull.size() > 0) {
                        mAddQty2.setText(mSubDataNull.size() + "");
                    }
                    mAdapter.notifyDataSetChanged();

                    break;
                case 0:
                    DialogUtil.dismissDialog(accessNetDialog);
                    mAdapter.notifyDataSetChanged();
                    String obj = (String) msg.obj;
                    Toast.makeText(InventryActivity.this, "" + obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    DialogUtil.dismissDialog(accessNetDialog);
                    mAdapter.notifyDataSetChanged();
                    String str = (String) msg.obj;
                    set_Dialog(str);

                    break;
            }
            return false;
        }
    });


    private PopupMenu popupMenu;

    //弹出菜单
    public void onPopupButtonClick(View button) {
        //创建PopupMenu对象
        popupMenu = new PopupMenu(this, button);
        //将R.menu.popup_menu菜单资源加载到popup菜单中
        getMenuInflater().inflate(R.menu.inventory_popup_menu, popupMenu.getMenu());
        //为popup菜单的菜单项单击事件绑定事件监听器
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.inventory_dao) {
                    InventoryRecordPopWindow scanRecordPopWindow = new InventoryRecordPopWindow(mContext, mDataList);
                    scanRecordPopWindow.setOnSelectScanRecordItemClickListener(InventryActivity.this);
                    // setBackgroundBlack(all_choice_layout, 0);
                    scanRecordPopWindow.showAsDropDown(new View(InventryActivity.this));

                } else if (item.getItemId() == R.id.inventory_qing) {

                    final int i = mManager.dedeteData(3);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(InventryActivity.this, "清除" + i + "数据", Toast.LENGTH_SHORT).show();
                            mDataList.clear();
                            mAddQty1.setText("0");
                            mAddQty2.setText("0");
                            mAdapter.setListDataBean(mDataList);
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
                return false;
            }
        });
        popupMenu.show();
    }

    private void export() {
        final ProgressDialog progressDialog = ProgressDialog.show(this, "", "正在导出数据请稍等");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
        intiData();
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                File file = Directory.getExcelFile();

                try {
                    ExcelUtils.write(file, peopleRecyclerAdapter.getPeoples());
                } catch (final IOException e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(InventryActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });


                    return null;
                } catch (final WriteException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(InventryActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return null;
                }
                return file.getAbsolutePath();
            }

            @Override
            protected void onPostExecute(String path) {
                progressDialog.dismiss();
                if (TextUtils.isEmpty(path))
                    Toast.makeText(InventryActivity.this, "Gagal mengekspor", Toast.LENGTH_SHORT).show();
                else

                    Toast.makeText(InventryActivity.this, "Berhasil mengekspor" + path, Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }

    private void intiData() {
        List<InventorySub> subDataList = mManager.findSubDataList();
        peopleRecyclerAdapter = new PeopleRecyclerAdapter();
        peopleRecyclerAdapter.add(new People("库位", "条码", "款式", "实际数", "多于", "差异"));
        for (int i = 0; i < subDataList.size(); i++) {
            peopleRecyclerAdapter.add(new People
                    ((subDataList.get(i).getLocation()), (subDataList.get(i).getBarode()), (subDataList.get(i).getCode()), (subDataList.get(i).getDiscNumber() + ""), (subDataList.get(i).getMoreThan() + ""), (subDataList.get(i).getLessThan() + "")));
        }
    }

    @Override
    public void onSelectClickOKPop() {

    }

    @Override
    public void onSelectClickDismissPop() {
        get_qty(1);
    }

    public void set_Dialog(String strDialog) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(strDialog);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create();
        builder.setCancelable(false);
        builder.show();
    }
}
